// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "content/browser/cache_storage/cache_storage_operation.h"

#include "content/browser/cache_storage/cache_storage_histogram_macros.h"

namespace content {

namespace {
    const int kNumSecondsForSlowOperation = 10;
}

CacheStorageOperation::CacheStorageOperation(
    const base::Closure& closure,
    CacheStorageSchedulerClient client_type,
    scoped_refptr<base::SingleThreadTaskRunner> task_runner)
    : closure_(closure)
    , creation_ticks_(base::TimeTicks::Now())
    , client_type_(client_type)
    , task_runner_(std::move(task_runner))
    , weak_ptr_factory_(this)
{
}

CacheStorageOperation::~CacheStorageOperation()
{
    CACHE_STORAGE_SCHEDULER_UMA(TIMES, "OperationDuration", client_type_,
        base::TimeTicks::Now() - start_ticks_);

    if (!was_slow_)
        CACHE_STORAGE_SCHEDULER_UMA(BOOLEAN, "IsOperationSlow", client_type_,
            false);
}

void CacheStorageOperation::Run()
{
    start_ticks_ = base::TimeTicks::Now();

    task_runner_->PostDelayedTask(
        FROM_HERE, base::Bind(&CacheStorageOperation::NotifyOperationSlow, weak_ptr_factory_.GetWeakPtr()),
        base::TimeDelta::FromSeconds(kNumSecondsForSlowOperation));
    closure_.Run();
}

void CacheStorageOperation::NotifyOperationSlow()
{
    was_slow_ = true;
    CACHE_STORAGE_SCHEDULER_UMA(BOOLEAN, "IsOperationSlow", client_type_, true);
}

} // namespace content
